package com.springcloud.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.springcloud.commons.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/**
 * 统一限流拦截器
 */
@Component
public class RateLimiterFiler extends ZuulFilter {

//    @Value("")
//    int rateNumber;
    static Logger log = LoggerFactory.getLogger(RateLimiterFiler.class);
    //200代表一秒最多多少个
    private static final RateLimiter rateLimiter = RateLimiter.create(1000);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        try {
            if(!rateLimiter.tryAcquire()) {
                log.warn("访问人数过多");
                RequestContext ctx = RequestContext.getCurrentContext();
                // Remove error code to prevent further error handling in follow up filters
                // 删除该异常信息,不然在下一个过滤器中还会被执行处理
                ctx.remove("throwable");
                // 根据具体的业务逻辑来处理
                ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                ctx.getResponse().setContentType("text/html;charset=UTF-8");
                Result result = new Result();
                result.setMsg("访问人数过多,请刷新重试~!");
                result.setSuccess(false);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(result);
                ctx.setResponseBody(json);
            }

        } catch (Exception ex) {
            log.error("Exception filtering in custom error filter", ex);
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }
}
